#include "communicationmanager.h"
#include "widget.h"



CommunicationManager::CommunicationManager(QObject *parent)
    : QObject{parent},received(0),serial(new QSerialPort(this)),protocol(new ProtocolHandler),sendFlag(true)
{
    //接收数据
    connect(serial, &QSerialPort::readyRead, this, &CommunicationManager::dataReceived);
}

//进行串口通信
void CommunicationManager::setupSerialPort(const QString &portName, int baudRate, QSerialPort::Parity parity, QSerialPort::DataBits dataBits, QSerialPort::StopBits stopBits)
{
    if (serial->isOpen()) {
        serial->close();
    }

    serial->setPortName(portName);
    serial->setBaudRate(baudRate);
    serial->setDataBits(dataBits);
    serial->setParity(parity);
    serial->setStopBits(stopBits);
    serial->setFlowControl(QSerialPort::NoFlowControl); //流控制

    if (serial->open(QIODevice::ReadWrite)) {
        QMessageBox::information(nullptr, "连接成功", "串口已成功打开");
    } else {
        QMessageBox::critical(nullptr, "连接失败", "无法打开串口，请检查设备和参数");
    }
}

//发送数据
void CommunicationManager::sendData(const QByteArray &data)
{
    if (serial->isOpen()&&sendFlag) {
        serial->flush();
        serial->write(data); // 发送数据
        qDebug() << "Data sent:" << data.toHex();
    } else {
        qDebug() << "Serial port is not open or sendFlag not valid";
    }
}
//停止发送数据
void CommunicationManager::stopSendData()
{
    sendFlag = false;
}

//将sendFlag设为true
void CommunicationManager::sengFlagTrue()
{
    sendFlag = true;
}

//接收到数据的槽函数
void CommunicationManager::dataReceived()
{
    QByteArray newData = serial->readAll();    // 从串口读取所有可用数据
    qDebug() << "接收到数据newData:" << newData.toHex();
    qDebug() << "接收到数据newData的长度:" << newData.size();

    emit dataUiUpdata(newData);

    // 获取单例的 Widget 实例
    Widget* widget = Widget::getInstance();
    widget->controlResponse.clear();
    widget->responseForPacket.clear();

    if (newData.size() == 9) {
        qDebug()<<"接收到数据载入响应";
        widget->responseForPacket = newData;
        qDebug() << "responseForFirstPacket" << widget->responseForPacket.toHex();
    }
    else if (newData.size() == 8) {
        qDebug()<<"接收到控制命令响应";
        widget->controlResponse = newData;
        qDebug() << "controlResponse:" << widget->controlResponse.toHex();
    }
    else {
        QMessageBox::critical(nullptr, tr("接受失败"), tr("响应非法，长度不匹配"));
    }
}

